package com.gt.gt_securitytest.config;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.gt.gt_securitytest.entity.MyUserDetails;
import com.gt.gt_securitytest.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import java.util.function.Supplier;

@Component
public class TokenAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext requestAuthorizationContext) {
        //获得请求request
        HttpServletRequest request = requestAuthorizationContext.getRequest();
        //获得请求地址
        StringBuffer requestURL = request.getRequestURL();
        //获得token
        String token = request.getHeader("token");
        //解析token
        Claims jsonObject = JwtUtil.parseJWT("gtboy", token); //claims是map，对象判空用ObjectUtils
        if (ObjectUtil.isEmpty(jsonObject))
            return new AuthorizationDecision(false);

        /*
        * jsonObject是一个map，key-user对应的是对象
        * */
        //获得Details，从token中
        Object user = jsonObject.get("user");
        String jsonString = JSON.toJSONString(user);
        MyUserDetails myUserDetails = JSONObject.parseObject(jsonString, MyUserDetails.class);
        //把获得的details放入SecurityHolder中
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(myUserDetails, myUserDetails.getPassword(), myUserDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //查看权限
        if(myUserDetails.getRoles().contains("ADMIN")){
            if("/hello/admin".equals(requestURL)){
                return new AuthorizationDecision(true);
            }
        }
        if(myUserDetails.getRoles().contains("USER")){
            if("/hello/user".equals(requestURL)){
                return new AuthorizationDecision(true);
            }
        }
        return new AuthorizationDecision(false);
    }
}
